package com.beauty.ui;

import java.util.LinkedList;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.beauty.adapter.ArticleAdapter;
import com.beauty.api.ApiClient;
import com.beauty.common.AnimateFirstDisplayListener;
import com.beauty.common.UpdateManager;
import com.beauty.common.Utils;
import com.beauty.model.ArticleModel;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.hk.beauty.R;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;

public class Main extends SlidingFragmentActivity {

	private ImageButton imgbtn_top_left;
	private static int catid = 0;// 类别id
	private static String title;// 标题
	private PullToRefreshListView main_list;
	ArticleAdapter articleAdapter;
	LinkedList<ArticleModel> listM;
	TextView tv_top_center;
	boolean isExit = false;
	int minid;
	public static ImageLoader imageLoader = ImageLoader.getInstance();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);

		AppManager.getAppManager().addActivity(this);
		
		imageLoader.init(AnimateFirstDisplayListener.getConfig(getApplicationContext()));
		
		imgbtn_top_left = (ImageButton) this.findViewById(R.id.imgbtn_top_left);
		imgbtn_top_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				toggle();// 打开关闭左侧菜单
			}
		});
		// 初始化滑动菜单
		initSlidingMenu(savedInstanceState);

		main_list = (PullToRefreshListView) findViewById(R.id.main_list);
		main_list.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				LoadMoreList();
			}
		});
		ListView actualListView = main_list.getRefreshableView();
		registerForContextMenu(actualListView);
		main_list.setMode(Mode.PULL_FROM_END);

		SetData();
		LoadList();

		// 检查软件更新
		UpdateManager manager = new UpdateManager(Main.this);
		manager.checkUpdate();
	}
	
	

	/**
	 * 初始化滑动菜单
	 */
	private void initSlidingMenu(Bundle savedInstanceState) {
		// 设置滑动菜单的视图
		setBehindContentView(R.layout.menu_frame);
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.menu_frame, new LeftMenu()).commit();
		// 实例化滑动菜单对象
		SlidingMenu sm = getSlidingMenu();
		// 设置滑动阴影的宽度
		sm.setShadowWidthRes(R.dimen.shadow_width);
		// 设置滑动阴影的图像资源
		sm.setShadowDrawable(R.drawable.shadow);
		// 设置滑动菜单视图的宽度
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		// 设置渐入渐出效果的值
		sm.setFadeDegree(0.35f);
		// 设置触摸屏幕的模式
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
	}

	/**
	 * 加载列表数据
	 */
	public void LoadList() {
		if (Utils.checkNetWork(this, true)) {
			new Thread(new ReceiveThread()).start();
		}
	}

	class ReceiveThread implements Runnable {
		@Override
		public void run() {
			listM = ApiClient.getSingle().GetarticleList(catid, 0);
			handler.sendEmptyMessage(1);
		}
	}

	/**
	 * 加载更多数据
	 */
	public void LoadMoreList() {
		if (Utils.checkNetWork(this, true)) {
			new Thread(new ReceiveThread2()).start();
		}
	}

	class ReceiveThread2 implements Runnable {
		@Override
		public void run() {
			if (listM != null && listM.size() > 0) {
				minid = listM.get(listM.size() - 1).getId();
				LinkedList<ArticleModel> listMore = ApiClient.getSingle()
						.GetarticleList(catid, minid);
				if (listMore.size() > 0) {
					for (int i = 0; i < listMore.size(); i++) {
						listM.add(listMore.get(i));
					}
					handler.sendEmptyMessage(2);
				} else {
					handler.sendEmptyMessage(4);
				}
			} else {
				handler.sendEmptyMessage(4);
			}
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 1) {
				if (listM != null) {
					articleAdapter = new ArticleAdapter(getBaseContext(), listM);
					main_list.setAdapter(articleAdapter);
				}
			} else if (msg.what == 2) {
				articleAdapter.notifyDataSetChanged();
				main_list.onRefreshComplete();
			} else if (msg.what == 3) {
				main_list.onRefreshComplete();
			} else if (msg.what == 4) {
				Toast.makeText(getApplicationContext(), "没有图片了,换个栏目看看", 1)
						.show();
				main_list.onRefreshComplete();
			}
		}
	};

	/**
	 * 设置数据
	 */
	public void SetData() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			catid = Integer.valueOf(bundle.getString("catid"));
			title = bundle.getString("title");
			tv_top_center = (TextView) this.findViewById(R.id.tv_top_center);
			tv_top_center.setText(title);
		}
	}

	/**
	 * 监听返回--是否退出程序
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = true;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setTitle("主人不再爱我了吗？");
			builder.setPositiveButton("下次再看",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							// 退出
							AppManager.getAppManager()
									.AppExit(getBaseContext());
						}
					});
			builder.setNegativeButton("再留会",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.show();
		} else {
			flag = super.onKeyDown(keyCode, event);
		}
		return flag;
	}

}
